import puppeteer from "puppeteer";
import {createArticle, getUserByName} from "../util/Article.js";
import {htmlToJson} from "../util/htmlToJson.js";
import {createData} from "../util/addData.js";
import {queryKeyword} from "./keyword.js";
const url = `https://weixin.sogou.com/weixinwap?query=`;
export const getHtml = async (wechatAccount='老飘讲故事')=>{
    console.log(`开始抓取公众号 ${url}${wechatAccount}`)
   try{
       // 启动一个浏览器实例
       const browser = await puppeteer.launch();

       // 创建一个页面实例
       const page = await browser.newPage();

       // 载入指定的 URL
       await page.goto(`${url}${wechatAccount}`);

       // 等待元素加载完成
       await page.waitForSelector('.wx-news-list2');

       // 获取指定元素
       const elementHandle = await page.$('.wx-news-list2');

       // 获取第一个 li 元素的 HTML 内容
       const firstLiHTML = await page.$eval('.wx-news-list2 li:first-child', li => li.outerHTML);

       // 关闭浏览器
       await browser.close();

       const doc = htmlToJson(firstLiHTML);
       const data = await getUserByName(doc.wechat_id)
       if(data&&data.timestamp===doc.timestamp){
           return '数据已存在'
       }
       const res = await createData(doc,'Article')
       const hookData = await queryKeyword(res.name)
       await webHook(res,hookData)
   }catch (e) {
       console.log(e.message)
   }

}

/**
 * 通知链接
 * @param data
 * @param hookData
 * @returns {Promise<void>}
 */
const webHook  = async (data,hookData) => {
    console.log(data,hookData)
    console.log('开始通知')
}
